package top.go2do.email.business.email.controller;

import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import top.go2do.email.business.email.module.EmailCodeForm;
import top.go2do.email.business.email.module.RegisterDTO;
import top.go2do.email.business.email.module.RegisterForm;
import top.go2do.email.business.email.service.EmailService;
import top.go2do.email.business.email.service.EmailUserService;

/**
 * @Description
 * @Author xingyj
 * @CreateTime 2025/7/13 18:57
 */
@Slf4j
@RequestMapping("/email")
@RestController
public class EmailController {

    @Autowired
    private EmailService emailService;

    @Autowired
    private EmailUserService emailUserService;

    @PostMapping("/send-register-code")
    public void sendRegisterCode(@Valid @RequestBody EmailCodeForm form) {
        log.info("send code email:{}", form.getEmail());
        emailService.sendVerificationCode(form.getEmail());
    }

    @PostMapping("/register")
    void register(@Valid @RequestBody RegisterForm form) {
        log.info("RegisterForm:{}", form);
        /**
         * step1: 校验邮箱验证码是否正确
         */
        emailService.checkVerificationCode(form.getEmail(), form.getCaptcha());

        /**
         * step2: 检查邮箱是否已注册
         */
        String appId = form.getAppId();
        String email = form.getEmail();
        emailUserService.judgeEmailUserExist(appId, email);

        /**
         * step3: 密码（密文）解密后，检查设置的是否符合规则
         */
        String passwordHash = form.getPasswordHash();
        // TODO: 解密得到明文密码
        String passwordRaw = passwordHash;


        /**
         * step4: 创建用户
         */
        RegisterDTO registerDTO = new RegisterDTO();
        registerDTO.setAppId(appId);
        registerDTO.setEmail(email);
        registerDTO.setPassword(passwordRaw);
        emailUserService.createEmailUser(registerDTO);
    }

}
